const { user } = require('../config/databaseConfig');
const userDao = require('../dao/userDao')
const setToken = require('../util/token')

const userController = {
    login:async function(req,resp){
        console.log('登录判断');
        const userName = req.body.userName
        const password = req.body.password

        try{
            const user = await userDao.getUserByUname(userName) //根据用户名获取用户信息

            if(user.length === 0) {
                resp.status(200).send({
                    msg:'用户不存在'
                })
            }else {
                if(user[0].password === password) {
                    const token = setToken.createToken({
                        uid:user[0].id,
                        exp: Date.now() + 1000*60*60*24 //过期时间
                    }) //生成token

                    const searchProps = [token,userName]

                    try {
                        await userDao.addUserToken(searchProps)
                    } catch (error) {
                        console.log('err',err);
                        resp.status(500).json({
                            msg: '抱歉，服务器可能出现了问题，技术小哥正在维修...'
                        })
                    }
                    
                    resp.status(200).json({
                        msg:'登录成功',
                        success:true,
                        userName,
                        token
                    })
                }else {
                    resp.status(200).json({
                        msg:'账号密码不匹配'
                    })
                }
            }
        }catch(err) {
            console.log('err',err);
            resp.status(500).json({
                msg: '抱歉，服务器可能出现了问题，技术小哥正在维修...'
            })
        }
    },
    async getData(req,resp){
        const token = setToken.getToken(req) //获取token
        let payload = null
        try {
            payload = setToken.getPayload(token)
        } catch (error) {
            console.log('err:',error);
            resp.status(200).send({
                msg:'token无效'
            })
        }
        let user = [];
        try{
            user = await userDao.getData({
                searchSql: 'select * from user where id=?',
                props:[payload.sub]
            })
        }catch(err) {
            console.log('err:',err);
            resp.status(500).send({
                msg:'服务器错误'
            })
        }

        user.length === 0 ? resp.status(200).send({
            msg:'token无效'
        }) : resp.status(200).send({
            data:{
                articles:['白鹿原','平凡的世界']
            },
            success:true
        })
        
    }
}

module.exports = userController